package com.jackrain.nea.fc.pos.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.pos.api.ViewDLRetailStoBillSaveCmd;
import com.jackrain.nea.fc.pos.mapper.ViewDLRetailStoBillMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * 零售对账单F4->中间表->FC
 *
 * @author wuwenxue
 * @date 2018/05/14
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "pos")
public class ViewDLRetailStoBillSaveCmdImpl extends CommandAdapter implements ViewDLRetailStoBillSaveCmd {

    @Autowired
    PostDubbleEvent postDubbleEvent;

    @Autowired
    private QueryUserUtil queryUserUtil;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewDLRetailStoBillSaveCmdImpl-->param-->{}",param);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }

        JSONArray paramArray = param.getJSONArray("data");
//        log.debug("paramArray------>" + paramArray);
        log.debug("ViewDLRetailStoBillSaveCmdImpl--paramArray-->{}",paramArray);

        JSONArray errorArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray successIds = new JSONArray();
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject errorJson = new JSONObject();
            JSONObject tranJson = paramArray.getJSONObject(i);

            JSONObject zbJS = tranJson.getJSONObject("DL_T_RETAIL_CHARGE_TRANSFER");
            JSONArray itemJS = tranJson.getJSONArray("DL_T_RETAIL_CHARGE_ITEM");
            JSONArray stroeArray = tranJson.getJSONArray("DL_T_RETAIL_C_STORE");
            try {

                /*******处理主表数据********/
                String idList = zbJS.getString("IDLIST");

                String oprEcode = zbJS.getString("OPR_ECODE");
                String oprEname = zbJS.getString("OPR_ENAME");
                String cpCStoreEcode = zbJS.getString("CP_C_STORE_ECODE");
                Long bill_date = zbJS.getLong("BILL_DATE");
                String isDelOrder = zbJS.getString("IS_DEl_ORDER");
                //主表BILL_NO
                String billNo = zbJS.getString("BILL_NO");

                Date billDate = TypeUtils.castToDate(bill_date + "000000");

                Long storeID = null;
                if (null == cpCStoreEcode) {
                    throw new NDSException("店仓编码为空！");
                } else {
                    //跨库查询
                    JSONObject whereJs = new JSONObject();
                    whereJs.put("ECODE", cpCStoreEcode);
                    HashMap h = QueryCpUtil.queryCP("CP_C_STORE", "ID", whereJs);
                    if (null != h && h.size() > 0) {
                        storeID = TypeUtils.castToLong(h.get("ID"));
                    } else {
                        throw new NDSException("店仓查询为空！  店仓编码:" + cpCStoreEcode);
                    }
                }

                User user = queryUserUtil.getUser(oprEcode);
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlreatilStoBill",
                        new HashMap(16));
                //当前登录pos的用户ID
                Integer operatorId = user.getId();

                /*******处理明细表数据********/
                JSONArray itemArray = new JSONArray();
                for (int j = 0; j < itemJS.size(); j++) {
                    JSONObject itemJson = itemJS.getJSONObject(j);

                    //现金
                    BigDecimal money = itemJson.getBigDecimal("MONEY");
                    //银行卡
                    BigDecimal bankcard = itemJson.getBigDecimal("BANKCARD");
                    //支付宝
                    BigDecimal alipay = itemJson.getBigDecimal("ALIPAY");
                    //微信
                    BigDecimal wechat = itemJson.getBigDecimal("WECHAT");
                    //购物卡
                    BigDecimal shopcard = itemJson.getBigDecimal("SHOPCARD");
                    //积分抵现
                    BigDecimal integral = itemJson.getBigDecimal("INTEGRAL");
                    //明细编号
                    String itemBillNo = itemJson.getString("ITEM_BILL_NO");

                    BigDecimal total = money.add(bankcard).add(alipay).add(wechat).add(shopcard);
                    //新增
                    JSONObject addStoreBIll = new JSONObject();

                    addStoreBIll.put("MONEY", money);
                    addStoreBIll.put("BANKCARD", bankcard);
                    addStoreBIll.put("ALIPAY", alipay);
                    addStoreBIll.put("WECHAT", wechat);
                    addStoreBIll.put("TOTAL", total);
                    addStoreBIll.put("SHOPCARD", shopcard);
                    addStoreBIll.put("INTEGRAL", integral);
                    addStoreBIll.put("BILL_NO", itemBillNo);

                    itemArray.add(addStoreBIll);
                }

                JSONObject storeBIll = new JSONObject();
                storeBIll.put("OperatorId", operatorId);
                storeBIll.put("OperatorEname", oprEname);
                storeBIll.put("StoreId", storeID);
                storeBIll.put("BILL_DATE", billDate);
                storeBIll.put("BILL_NO", billNo);
                storeBIll.put("IS_DEl_ORDER", isDelOrder);

                JSONObject fixcolumn = new JSONObject();
                fixcolumn.put("DL_B_STORE_BILL_ITEM", itemArray);
                fixcolumn.put("DL_B_STORE_BILL", storeBIll);
                fixcolumn.put("DL_B_RETAIL_C_STORE", stroeArray);

                event.put("param", fixcolumn);
//                log.debug("fixcolumn_data->" + fixcolumn);
                accesLogger.info("ViewDLRetailStoBillSaveCmdImpl--fixcolumn-->{}",fixcolumn);

                querySession.setEvent(event);
                String addNotic = "com.jackrain.nea.retail.api.ViewDlRetailStoBillSetCmd:1.0:pos";
                //调用标准服务
                JSONObject retAddJo = postDubbleEvent.executePostDubble(addNotic, querySession);
//                log.debug("retAddJo" + retAddJo);
                accesLogger.info("ViewDLRetailStoBillSaveCmdImpl--retAddJo-->{}",retAddJo);

                if (retAddJo.containsKey("code") && (int) retAddJo.get("code") != 0) {
                    errorJson.put("key", idList);
                    if (null == retAddJo.get("message")) {
                        errorJson.put("message", "零售对账单处理时报错");
                    } else {
                        errorJson.put("message", "零售对账单处理时报错->" + retAddJo.get("message"));
                    }
                    errorArray.add(errorJson);
                    continue;
                }
                queryDataArray.add(fixcolumn);
                successIds.add(idList);

            } catch (Exception e) {
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                String idList = zbJS.getString("IDLIST");
                errorJson.put("key", idList);
                errorJson.put("message", error);
                errorArray.add(errorJson);
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        vh.put("queryDataArray", queryDataArray);
        vh.put("successIds", successIds);

        return vh;
    }

}
